<template>
  <div class="login">
    <div class="loginTop">
      <van-icon name="revoke" size="25" @click="$router.go(-1)" />
      <span>欢迎登录</span>
    </div>
    <div class="loginContent">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="user.phone" name="phone" label="手机" placeholder="手机号码" :rules="userFormRules.phone" />
          <van-field v-model="user.password" type="password" name="password" label="密码" placeholder="密码" :rules="userFormRules.password" />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { mapMutations, mapState } from 'vuex'
import { useStore } from 'vuex'
import { getPhoneLogin } from '@/api/login.js'
import { useRouter } from 'vue-router'
export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const store = useStore()
    // 登录表单的手机、密码数据
    const user = reactive({ phone: '', password: '' })
    // 登录表单的验证规则
    // 手机号码正则
    const pattern = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
    const userFormRules = reactive({
      phone: [
        { required: true, message: '请填写手机号' },
        { pattern, message: '请正确填写手机号' }
      ],
      password: [{ required: true, message: '请填写密码' }]
    })

    // 监听登录事件,表单提交验证通过时请求登录数据
    const onSubmit = async values => {
      console.log(values)
      let res = await store.dispatch('getLogin', values)
      //如果返回的code等于200，说明登录成功，就跳转个人中心页面
      if (res.code === 200) {
        sessionStorage.setItem('token', res.token)
        router.push('/infoUser')
      } else {
        alert('登录失败')
      }
    }

    return { user, userFormRules, onSubmit }
  }
}
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 14rem;
  .loginTop {
    width: 100%;
    height: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .van-icon {
      position: absolute;
      left: 0;
    }
    span {
      font-size: 0.6rem;
      font-weight: 500;
    }
  }
  .loginContent {
    margin: 0.4rem 0;
  }
}
</style>